<script lang="ts" setup>
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { forceLogout, getOnlineList } from '@/api/system/online'
import type { IGetOnlineList, IGetOnlineListRes } from '@/api/system/online/type'
import { warnBox } from '@/utils/utils'
import { formatDate } from '@/utils/day'

// form
const formValue = ref<IGetOnlineList>({
	ipaddr: '',
	userName: ''
})
const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '登录地址',
		prop: 'ipaddr'
	},
	{
		type: 'input',
		label: '用户名称',
		prop: 'userName'
	}
])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<IGetOnlineListRes[]>([])
const columns = ref<TableColums[]>([
	{
		label: '会话编号',
		prop: 'tokenId'
	},
	{
		label: '登录名称',
		prop: 'userName'
	},
	{
		label: '所属部门',
		prop: 'deptName'
	},
	{
		label: '主机',
		prop: 'ipaddr'
	},
	{
		label: '登录地点',
		prop: 'loginLocation'
	},
	{
		label: '操作系统',
		prop: 'os'
	},
	{
		label: '浏览器',
		prop: 'browser'
	},
	{
		label: '登录时间',
		prop: 'loginTime',
		formatter: val => formatDate(val.loginTime),
		showOverflowTooltip: true
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 120
	}
])

const getTableData = async () => {
	try {
		loading.value = true
		const res = await getOnlineList({
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value
		})
		tableData.value = res.data
		page.value.total = res.data.length || 0
	} finally {
		loading.value = false
	}
}

const forceOut = async (row: IGetOnlineListRes) => {
	await warnBox({
		message: `是否确认强退名称为"${row.userName}"的用户?`
	})
	const res = await forceLogout(row.tokenId)
	ElMessage.success(res.msg)
	getTableData()
}

onMounted(() => {
	getTableData()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData.slice((page.currentPage - 1) * page.pageSize, page.currentPage * page.pageSize)"
				:columns="columns"
				:loading="loading"
				:page="page"
				style="width: 100%"
			>
				<template #action="{ row }">
					<el-button
						type="danger"
						link
						@click="forceOut(row)"
					>
						强退
					</el-button>
				</template>
			</QTable>
		</div>
	</div>
</template>
